import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Collapse, List, Empty, Spin, Button, ConfigProvider } from 'antd';
import { RightOutlined, BookOutlined } from '@ant-design/icons';
import { chapterAPI, modelAPI } from '../../api/api';
import './UserHomeV2.css';

function UserHomeV2() {
  const navigate = useNavigate();
  const [chaptersWithModels, setChaptersWithModels] = useState([]);
  const [activeKeys, setActiveKeys] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const loadData = async () => {
    try {
      setLoading(true);
      const chapters = await chapterAPI.getAll();
      
      const chaptersWithModelsData = await Promise.all(
        chapters.map(async (chapter) => {
          try {
            const models = await modelAPI.getAll(chapter.id);
            return { ...chapter, models };
          } catch {
            return { ...chapter, models: [] };
          }
        })
      );
      
      setChaptersWithModels(chaptersWithModelsData);
      setError(null);
    } catch (err) {
      setError('加载数据失败: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  if (loading) {
    return (
      <div className="user-home-v2">
        <div className="loading-container">
          <Spin size="large">
            <div style={{ paddingTop: 50 }}>加载中...</div>
          </Spin>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="user-home-v2">
        <div className="error-container">
          <Empty description={error} />
          <Button type="primary" onClick={loadData}>重试</Button>
        </div>
      </div>
    );
  }

  return (
    <ConfigProvider
      theme={{
        token: {
          colorPrimary: '#1890ff',
          colorLink: '#1890ff',
          borderRadius: 8,
        },
      }}
    >
      <div className="user-home-v2">
        <div className="header-banner">
          <div className="banner-content">
            <div className="banner-text">
              <h1>图解几何模型</h1>
            </div>
            <img src="/geometry/logo.png" alt="Logo" className="banner-logo" />
          </div>
        </div>

        <div className="content-section">
          {chaptersWithModels.length === 0 ? (
            <Empty 
              icon={<BookOutlined style={{ fontSize: 64, color: '#bfbfbf' }} />}
              description="暂无课程内容" 
            />
          ) : (
            <Collapse
              activeKey={activeKeys}
              onChange={setActiveKeys}
              className="chapters-collapse"
              expandIconPosition="end"
              items={chaptersWithModels.map((chapter) => ({
                key: chapter.id,
                label: (
                  <div className="chapter-header-content">
                    <span className="chapter-title">{chapter.title}</span>
                  </div>
                ),
                className: "chapter-panel",
                children: chapter.models && chapter.models.length > 0 ? (
                  <List
                    dataSource={chapter.models}
                    renderItem={(model, index) => (
                      <List.Item
                        className="model-list-item"
                        onClick={() => navigate(`/model/${model.id}`)}
                      >
                        <div className="model-item-content">
                          <span className="model-number">
                            {String(index + 1).padStart(2, '0')}
                          </span>
                          <span className="model-title">{model.title}</span>
                          <RightOutlined className="model-arrow" />
                        </div>
                      </List.Item>
                    )}
                  />
                ) : null
              }))}
            />
          )}
        </div>
      </div>
    </ConfigProvider>
  );
}

export default UserHomeV2;

